function findLargestTransparentAreaByUrl(imageSrc) {
    return new Promise((resolve, reject) => {
        // 创建 Image 对象
        const img = new Image();
        img.crossOrigin = "Anonymous"; // 允许跨域图片处理

        // 添加时间戳参数防止缓存
        const timestamp = Date.now();
        imageSrc = imageSrc + "?bid=my&ts=" + timestamp;

        // 用 fetch 获取远程图片
        fetch(imageSrc)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Network error: ${response.status}`);
                }
                return response.blob(); // 将响应转为 Blob
            })
            .then(blob => {
                // 创建 Object URL
                const url = URL.createObjectURL(blob);
                img.src = url;

                // 添加 onload 事件处理程序
                img.onload = () => {
                    console.log('图片已加载', new Date());

                    // 准备释放Object URL
                    URL.revokeObjectURL(url);

                    const imageWidth = img.naturalWidth || img.width;
                    const imageHeight = img.naturalHeight || img.height;

                    // 检查尺寸
                    if (imageWidth !== 260 || imageHeight !== 160) {
                        console.warn(`图片尺寸为${imageWidth}x${imageHeight}，非260x160，跳过处理`);
                        resolve(null);
                        return;
                    }

                    // 准备处理像素
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    canvas.width = imageWidth;
                    canvas.height = imageHeight;

                    // 确保绘制图像没有缩放
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                    // 获取图像数据
                    const imageData = ctx.getImageData(0, 0, imageWidth, imageHeight);
                    const data = imageData.data;

                    let leftMostX = null; // 存储最左边透明像素的X坐标

                    // 双循环扫描所有像素
                    for (let x = 0; x < imageWidth; x++) {
                        for (let y = 0; y < imageHeight; y++) {
                            // 计算像素索引 (RGBA) - 4 bytes per pixel
                            const idx = (y * imageWidth + x) * 4;

                            // 检查alpha值 (第4字节)
                            if (data[idx + 3] <100) {
                                leftMostX = x; // 找到透明像素
                                console.log(`在位置(${x},${y})找到透明像素`);
                                break; // 跳出当前列的扫描
                            }
                        }
                        // 如果已经找到最左透明像素，结束扫描
                        if (leftMostX !== null) break;
                    }

                    // 结果处理
                    if (leftMostX === null) {
                        console.log('未找到透明像素');
                    } else {
                        console.log(`找到的最左边透明像素X坐标: ${leftMostX}`);
                    }

                    resolve(leftMostX);
                };

                // 错误处理
                img.onerror = (err) => {
                    URL.revokeObjectURL(url);
                    console.error("图片加载错误:", err);
                    reject(new Error("图片加载失败"));
                };
            })
            .catch(error => {
                console.error("图片获取错误:", error);
                reject(new Error("无法获取图片数据"));
            });
    });
}


/**
 * 模拟滑块验证码操作（支持重复调用）
 * @param {number} targetX - 目标滑动距离（像素）
 * @returns {Promise<void>}
 */
async function simulateSlider(targetX) {
    // 获取 DOM 元素
    const sliderElement = document.querySelector('.captcha_slide_block');
    const sileMoved = document.querySelector('.captcha_slide_moved');
    const sliderContainer = document.querySelector('.captcha_canvas_wrapper');

    if (!sliderElement || !sileMoved || !sliderContainer) {
        throw new Error("未找到滑块元素！");
    }

    // 初始化状态
    let currentX = 0;
    let animationInterval = null;
    const steps = 30;
    const delay = 50;
    const offset = 20;
    const containerRect = sliderContainer.getBoundingClientRect();

    // 重置滑块位置
    sliderElement.style.left = "0";
    sileMoved.style.width = "0";

    // 生成随机抖动（最后 5 步禁用）
    function getRandomOffset(step) {
        return (step >= steps - 5) ? 0 : Math.random() * 4 - 2; // [-2, 2]
    }

    // 缓动函数（确保最终 progress=1）
    function easeInOutCubic(t) {
        if (t >= 1) return 1;
        return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
    }

    // 模拟鼠标按下
    function mouseDown() {
        const event = new MouseEvent('mousedown', {
            clientX: containerRect.left + currentX + offset,
            clientY: sliderElement.getBoundingClientRect().top,
            bubbles: true,
        });
        console.log("mouseDown",new Date().toLocaleString());
        sliderElement.dispatchEvent(event);
    }

    // 模拟鼠标移动（返回 Promise）
    function mouseMove() {
        console.log("mouseMove",new Date().toLocaleString());
        return new Promise((resolve) => {
            let step = 0;
            animationInterval = setInterval(() => {
                if (step < steps) {
                    const progress = easeInOutCubic(step / steps);
                    currentX = progress * targetX + getRandomOffset(step);

                    // 强制终点对齐
                    if (step === steps - 1) currentX = targetX;

                    // 更新滑块位置
                    sliderElement.style.left = `${currentX}px`;
                    sileMoved.style.width = `${currentX}px`;
                    console.log("sliderElement.style.left",sliderElement.style.left,new Date().toLocaleString());
                    // 触发事件
                    const event = new MouseEvent('mousemove', {
                        clientX: containerRect.left + currentX + offset,
                        clientY: sliderElement.getBoundingClientRect().top,
                        bubbles: true,
                    });
                    sliderElement.dispatchEvent(event);
                    step++;
                } else {
                    clearInterval(animationInterval);
                    resolve();
                }
            }, delay);
        });
    }

    // 模拟鼠标释放
    function mouseUp() {
        console.log("mouseUp",new Date().toLocaleString());
        const event = new MouseEvent('mouseup', {
            clientX: containerRect.left + currentX + offset,
            clientY: sliderElement.getBoundingClientRect().top,
            bubbles: true,
        });
        sliderElement.dispatchEvent(event);
    }

    // 执行滑动
    try {
        mouseDown();
        await mouseMove();
        await new Promise(resolve => setTimeout(resolve, 100)); // 确保动画完成
        mouseUp();
    } finally {
        if (animationInterval) clearInterval(animationInterval); // 清理残留
        start_move = false;
    }
}

var not_find_button_time = 0;

function simulateClick(element) {
    if (element) {
        // 滚动到元素
        scrollToElement(element);

        // 模拟鼠标移动
        simulateMouseMove(element);

        // 给用户一些时间查看元素
        setTimeout(() => {
            // 创建 MouseEvent 对象，表示鼠标点击事件
            const mouseEventOptions = {
                bubbles: true,
                cancelable: true,
                view: window
            };

            // 先触发 mousedown 事件
            const mouseDownEvent = new MouseEvent('mousedown', mouseEventOptions);
            element.dispatchEvent(mouseDownEvent);

            // 模拟鼠标按下后的延迟
            setTimeout(() => {
                // 创建和触发 mouseup 事件
                const mouseUpEvent = new MouseEvent('mouseup', mouseEventOptions);
                element.dispatchEvent(mouseUpEvent);

                // 模拟 mouseup 后的延迟
                setTimeout(() => {
                    // 创建和触发 click 事件
                    const clickEvent = new MouseEvent('click', mouseEventOptions);
                    element.dispatchEvent(clickEvent);
                }, getRandomDelay());
            }, getRandomDelay());
        }, getRandomDelay());
    } else {
        not_find_button_time++;
        console.log('元素未找到', not_find_button_time);
        if (not_find_button_time > 5) {
            page_reload();
        }
    }
}

// 获取一个范围在 100 到 500 毫秒之间的随机延迟
function getRandomDelay() {
    return Math.floor(Math.random() * (500 - 100 + 1)) + 100; // 返回 100ms 到 500ms 的随机数
}

// 滚动到元素
function scrollToElement(element) {
    const rect = element.getBoundingClientRect();
    window.scrollTo({ top: rect.top + window.scrollY - (window.innerHeight / 2), behavior: 'smooth' });
}

// 模拟鼠标移动
function simulateMouseMove(element) {
    const mouseMoveEvent = new MouseEvent('mousemove', {
        bubbles: true,
        cancelable: true,
        view: window,
        clientX: element.getBoundingClientRect().left + window.scrollX,
        clientY: element.getBoundingClientRect().top + window.scrollY
    });
    element.dispatchEvent(mouseMoveEvent);
}





function getPriceAndStockFromDetailPage(jsonObject,id){

    if(jsonObject['modules']['saleAttr'] && jsonObject['modules']['saleAttr']['multiLevelSaleAttribute'] && jsonObject['modules']['saleAttr']['multiLevelSaleAttribute']['sku_list']){
        var sku_list = jsonObject['modules']['saleAttr']['multiLevelSaleAttribute']['sku_list'];
        //console.log(sku_list);

        var stock_map = {};
        var index = 0;
        sku_list.forEach((item) => {
            if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
            }else{
                stock_map[index] = item['stock'];
            }
            index++;

        })

        var price = jsonObject['modules']['priceInfo']['salePrice']['amount'];

        var type = "sheinstock_s1";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        console.log(stock_map);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

        /*var all_color_list =[];
        if(jsonObject['info']['saleAttr']['mainSaleAttribute'] && jsonObject['info']['saleAttr']['mainSaleAttribute']['info']){
            jsonObject['info']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
                let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
                all_color_list.push(new_color_url);
            });
        }


        if(msg.data.have_order===true){
            console.log(all_color_list)
            type = "sheinstock_s1_new_url";
            chrome.runtime.sendMessage({ data: {type,id, all_color_list,price}, close: false });
        }*/

    }else if(jsonObject['modules']['productInfo']['stock']==0){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        let price = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }else if(jsonObject['modules']['saleAttr'] && !jsonObject['modules']['saleAttr']['multiLevelSaleAttribute']){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        let price = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }


}



function doWitdhDataJob(jsonObject,id,msg){

    if(jsonObject['code']=="200301"){
        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })

    }else if(jsonObject['info']['saleAttr'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list']){
        var sku_list = jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list'];
        //console.log(sku_list);

        var stock_map = {};
        var index = 0;
        sku_list.forEach((item) => {
            if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
            }else{
                stock_map[index] = item['stock'];
            }
            index++;

        })

        var price = jsonObject['info']['priceInfo']['salePrice']['amount'];

        var type = "sheinstock_s1";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        console.log(stock_map);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

        var all_color_list =[];
        if(jsonObject['info']['saleAttr']['mainSaleAttribute'] && jsonObject['info']['saleAttr']['mainSaleAttribute']['info']){
            jsonObject['info']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
                let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
                all_color_list.push(new_color_url);
            });
        }


        if(msg.data.have_order===true){
            console.log(all_color_list)
            type = "sheinstock_s1_new_url";
            chrome.runtime.sendMessage({ data: {type,id, all_color_list,price}, close: false });
        }

    }else if(jsonObject['info']['productInfo']['stock']==0){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }


}



function getStockByQuickView(jsonObject,id,msg){

    let this_good_id = msg.data.goods_id;
    if(jsonObject['code']=="200301"){
        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })

    }else if(jsonObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list']){

        var stock_map = {};
        jsonObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list'].forEach(item=>{
            item['sku_sale_attr'].forEach(item1=>{
                if(item1['attr_name_en']=='Size'){
                    stock_map[item1['attr_value_name']] = item['stock'];
                }
            });
        });

        var price = jsonObject['info']['goods']['getPrice']['salePrice']['amount'];

        var type = "sheinstock_s1";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        console.log(stock_map);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

        var all_color_list = [];
        jsonObject['info']['goods']['colorData']['colorList'].forEach(item=>{
            let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
            all_color_list.push(new_color_url);
        });

        if(msg.data.have_order===true){
            console.log(all_color_list)
            type = "sheinstock_s1_new_url";
            chrome.runtime.sendMessage({ data: {type,id, all_color_list,price}, close: false });
        }

    }else if(jsonObject['info']['productInfo']['stock']==0){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }


}




function page_reload(){

    let wait_time = getQueryString("time");
    let wait_time_int= parseInt(wait_time, 10);
    if(wait_time_int <=0){
        wait_time_int = 5000;
    }
    console.log("reload satrt",wait_time_int);
    setTimeout(() => {
        location.reload()
    },wait_time_int);
}

